<template>
  <div class="cart-container">
    <!-- 顶部导航栏 -->
    <div class="cart-header">
      <h1>我的购物车</h1>
    </div>

    <div v-loading="loading" element-loading-text="加载中..." class="cart-content-wrapper">
    <div v-if="error" class="error-container">
      <el-alert :title="error" type="error" show-icon />
    </div>

    <!-- 购物车为空的情况 -->
    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车还是空的，快去选购商品吧！" />
      <el-button type="primary" @click="navigateToHome">
        去购物
      </el-button>
    </div>

      <!-- 购物车商品列表 -->
      <div v-else class="cart-items-container">
        <!-- 表头 -->
        <div class="cart-table-header">
          <div class="table-column select-column">
            <el-checkbox v-model="selectAll" @change="(val: boolean | string | number) => handleSelectAll(val)" />
          </div>
          <div class="table-column product-info-column">商品信息</div>
          <div class="table-column price-column">单价</div>
          <div class="table-column quantity-column">数量</div>
          <div class="table-column subtotal-column">小计</div>
          <div class="table-column action-column">操作</div>
        </div>

        <!-- 商品列表 -->
        <div class="cart-items-list">
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <div class="table-column select-column">
              <el-checkbox v-model="item.selected" @change="() => handleItemSelect()" />
            </div>
            <div class="table-column product-info-column">
              <div class="product-info">
                <img :src="item.product.images[0] || item.product.imageUrl" alt="{{ item.product.name }}" />
                <div class="product-details">
                  <h3 class="product-name">{{ item.product.name }}</h3>
                  <p class="product-category">分类：{{ item.product.category.name }}</p>
                  <div v-if="item.priceChanged" class="price-change-alert">
                    <el-tag type="warning" size="small">价格已更新</el-tag>
                  </div>
                  <div v-if="item.product.stock < item.quantity" class="stock-alert">
                    <el-tag type="danger" size="small">库存不足</el-tag>
                  </div>
                </div>
              </div>
            </div>
            <div class="table-column price-column">
              ¥{{ item.currentPrice.toFixed(2) }}
            </div>
            <div class="table-column quantity-column">
              <div class="quantity-controls">
                <button class="quantity-btn minus" @click="decreaseQuantity(item)" :disabled="item.quantity <= 1">
                  -
                </button>
                <input type="number" v-model.number="item.quantity" min="1" :max="item.product.stock" @change="() => handleQuantityChange(item)" />
                <button class="quantity-btn plus" @click="increaseQuantity(item)" :disabled="item.quantity >= item.product.stock">
                  +
                </button>
              </div>
            </div>
            <div class="table-column subtotal-column">
              <span class="subtotal">¥{{ (item.currentPrice * item.quantity).toFixed(2) }}</span>
            </div>
            <div class="table-column action-column">
              <el-button type="text" @click="removeItem(item.id)" danger>
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="cart-footer">
          <div class="footer-left">
            <el-button type="text" @click="clearCart">清空购物车</el-button>
            <el-button type="default" @click="navigateToHome">继续购物</el-button>
          </div>
          <div class="footer-right">
            <div class="total-info">
              <span>已选商品 {{ selectedCount }} 件</span>
              <div class="total-price">
                合计：<span class="price-value">¥{{ totalPrice.toFixed(2) }}</span>
              </div>
            </div>
            <el-button type="primary" size="large" @click="checkout" :disabled="selectedCount === 0">
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { cartService } from '../../api/cartService';
import type { AxiosError } from 'axios';

// 定义购物车商品项的类型
interface CartItem {
  id: number;
  productId: number;
  quantity: number;
  unitPrice: number;
  currentPrice: number;
  availableQuantity: number;
  priceChanged: boolean;
  product: {
    id: number;
    name: string;
    images: string[];
    imageUrl?: string;
    stock: number;
    price: number;
    isActive: boolean;
    category: {
      id: number;
      name: string;
    };
  };
  selected: boolean;
}

// 定义API错误响应的类型
interface ApiErrorResponse {
  message?: string;
  [key: string]: any;
}

// 路由相关
const router = useRouter();

// 响应式数据
const cartItems = ref<CartItem[]>([]);
const loading = ref(true);
const error = ref('');
const selectAll = ref(false);

// 计算属性
const selectedItems = computed(() => cartItems.value.filter(item => item.selected));
const selectedCount = computed(() => selectedItems.value.reduce((total, item) => total + item.quantity, 0));
const totalPrice = computed(() => selectedItems.value.reduce((total, item) => total + item.currentPrice * item.quantity, 0));

// 方法
const navigateToHome = () => {
  router.push('/');
};

const fetchCartItems = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await cartService.getCart();
    // 根据后端API响应结构提取购物车项
    const items = response.data.cartItems || [];
    
    // 将获取到的购物车项添加选中状态
    cartItems.value = items.map((item: any) => ({
      ...item,
      selected: true // 默认选中所有商品
    }));
    selectAll.value = cartItems.value.length > 0;
  } catch (err) {
    const axiosError = err as import('axios').AxiosError<ApiErrorResponse>;
    error.value = axiosError.response?.data?.message || '获取购物车失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const handleSelectAll = (checked: boolean | string | number) => {
  const isChecked = Boolean(checked);
  cartItems.value.forEach(item => {
    item.selected = isChecked;
  });
};

const handleItemSelect = () => {
  selectAll.value = cartItems.value.every(item => item.selected);
};

const increaseQuantity = async (item: CartItem) => {
  if (item.quantity < item.product.stock) {
    try {
      await updateItemQuantity(item.id, item.quantity + 1);
    } catch (err) {
      ElMessage.error('更新数量失败');
    }
  }
};

const decreaseQuantity = async (item: CartItem) => {
  if (item.quantity > 1) {
    try {
      await updateItemQuantity(item.id, item.quantity - 1);
    } catch (err) {
      ElMessage.error('更新数量失败');
    }
  }
};

const handleQuantityChange = async (item: CartItem) => {
  if (item.quantity < 1) {
    item.quantity = 1;
  } else if (item.quantity > item.product.stock) {
    item.quantity = item.product.stock;
  }
  
  try {
    await updateItemQuantity(item.id, item.quantity);
  } catch (err) {
    ElMessage.error('更新数量失败');
  }
};

const updateItemQuantity = async (itemId: number, quantity: number) => {
  const response = await cartService.updateCartItem(itemId, { quantity });
  // 更新本地数据
  const item = cartItems.value.find(i => i.id === itemId);
  if (item) {
    item.quantity = quantity;
    item.unitPrice = response.data.data.cartItem.unitPrice;
  }
};

const removeItem = async (itemId: number) => {
  try {
    await ElMessageBox.confirm('确定要从购物车中移除该商品吗？', '确认移除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await cartService.removeFromCart(itemId);
    cartItems.value = cartItems.value.filter(item => item.id !== itemId);
    selectAll.value = cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
    ElMessage.success('商品已移除');
  } catch (err) {
    if ((err as any).name !== 'ElMessageBoxCancel') {
      ElMessage.error('移除失败');
    }
  }
};

const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await cartService.clearCart();
    cartItems.value = [];
    selectAll.value = false;
    ElMessage.success('购物车已清空');
  } catch (err) {
    if ((err as any).name !== 'ElMessageBoxCancel') {
      ElMessage.error('清空失败');
    }
  }
};

const checkout = () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请选择要结算的商品');
    return;
  }
  
  // 跳转到结算页面，可以传递选中的商品信息
  router.push({
    path: '/checkout',
    query: {
      selectedItems: JSON.stringify(selectedItems.value.map(item => ({
        id: item.id,
        productId: item.productId,
        quantity: item.quantity
      })))
    }
  });
};

// 组件挂载时获取购物车数据
onMounted(() => {
  fetchCartItems();
});
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.cart-header {
  padding: 20px;
  background-color: white;
  border-bottom: 1px solid #eee;
}

.cart-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.cart-content {
  padding: 20px;
  background-color: white;
  min-height: 500px;
}

.loading-container, .error-container, .empty-cart {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.empty-cart .el-button {
  margin-top: 20px;
}

.cart-items-container {
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
}

.cart-table-header {
  display: flex;
  background-color: #fafafa;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  font-weight: 600;
  color: #606266;
}

.table-column {
  display: flex;
  align-items: center;
}

.select-column {
  width: 80px;
}

.product-info-column {
  flex: 2;
}

.price-column {
  width: 120px;
  justify-content: center;
}

.quantity-column {
  width: 180px;
  justify-content: center;
}

.subtotal-column {
  width: 150px;
  justify-content: center;
}

.action-column {
  width: 100px;
  justify-content: center;
}

.cart-items-list {
  max-height: 600px;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.cart-item:hover {
  background-color: #fafafa;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.product-info img {
  width: 100px;
  height: 100px;
  object-fit: contain;
  background-color: #f9f9f9;
}

.product-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  color: #333;
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-category {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.price-change-alert, .stock-alert {
  margin-top: 4px;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  background-color: white;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  user-select: none;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.quantity-controls input {
  width: 60px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-left: none;
  border-right: none;
  text-align: center;
  outline: none;
}

.subtotal {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.footer-left {
  display: flex;
  gap: 20px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 30px;
}

.total-info {
  text-align: right;
}

.total-info > span {
  display: block;
  margin-bottom: 8px;
  color: #606266;
}

.total-price {
  font-size: 18px;
  color: #333;
}

.price-value {
  font-size: 24px;
  font-weight: 600;
  color: #f56c6c;
}

.footer-right .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .cart-table-header,
  .cart-item {
    grid-template-columns: 40px 2fr 1fr 1fr 1fr 100px;
  }
  
  .product-info img {
    width: 80px;
    height: 80px;
  }
}

@media (max-width: 992px) {
  .cart-table-header,
  .cart-item {
    grid-template-columns: 40px 1fr 1fr 1fr 1fr 80px;
  }
  
  .product-info img {
    width: 70px;
    height: 70px;
  }
  
  .product-name {
    font-size: 14px;
  }
  
  .price,
  .subtotal {
    font-size: 14px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-table-header {
    display: none;
  }
  
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 15px;
  }
  
  .table-column {
    width: 100% !important;
    justify-content: flex-start !important;
  }
  
  .product-info {
    flex-direction: row;
    align-items: flex-start;
  }
  
  .product-info img {
    width: 80px;
    height: 80px;
    margin-right: 15px;
  }
  
  .product-details {
    flex: 1;
  }
  
  .product-name {
    max-width: 100%;
    font-size: 16px;
  }
  
  .quantity-controls {
    display: flex;
    align-items: center;
    gap: 5px;
  }
  
  .quantity-btn {
    width: 30px;
    height: 30px;
    font-size: 16px;
  }
  
  .quantity-controls input {
    width: 40px;
    height: 30px;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
    padding: 15px;
  }
  
  .footer-left {
    gap: 10px;
  }
  
  .footer-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .total-info {
    text-align: left;
  }
  
  .price-value {
    font-size: 20px;
  }
  
  .footer-right .el-button {
    min-width: auto;
    padding: 10px 15px;
  }
}

@media (max-width: 480px) {
  .cart-container {
    padding: 10px;
  }
  
  .cart-header h1 {
    font-size: 20px;
  }
  
  .cart-item {
    padding: 10px;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .product-info img {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .footer-left {
    flex-direction: column;
    gap: 10px;
  }
  
  .footer-right {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .total-info {
    text-align: center;
  }
  
  .footer-right .el-button {
    width: 100%;
  }
}
</style>